package hero.mps.leet_code_7;

public class IntegerReverse {
    public static int reverse(int x) {
        String target = new StringBuilder().append(Math.abs(x)).reverse().toString();
        try {
            int result = Integer.parseInt(target);
            return (x < 0) ? result * -1 : result;
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    public static int reverse1(int x) {
        String target = reverseString(String.valueOf(Math.abs(x)));
        try {
            int result = Integer.parseInt(target);
            return (x < 0) ? result * -1 : result;
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    public static int reverse2(int x) {
        int result = 0;
        while (x != 0) {
            // 取出 x 的个位数
            int pop = x % 10;
            // 去掉 x 的个位数
            x /= 10;

            // 判断反转后的数是否会超过 Integer.MAX_VALUE
            if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && pop > 7)) return 0;

            // 判断反转后的数是否会小于 Integer.MIN_VALUE
            if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && pop < -8)) return 0;

            // 将取出的个位数添加到反转数的末尾
            result = result * 10 + pop;
        }
        // 返回反转后的数
        return result;
    }


    public static String reverseString(String str) {
        char[] chars = str.toCharArray();
        int n = chars.length - 1;
        for (int i = (n-1) >> 1; i >= 0; i--) {
            int k = n - i;
            char ci = chars[i];
            char ck = chars[k];
            chars[i] = ck;
            chars[k] = ci;
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        System.out.println(reverse2(901000));
    }
}
